/*
 * File:   server.c
 * Author: Miroslav
 *
 * Created on May 23, 2009, 11:04 PM
 */
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <pthread.h>

#define _REENTRANT

#define MYPORT 3335
#define BACKLOG 10

void comunicate_ptr(void *sock);

/*
 *
 */
int main() {

    int sockfd;
    struct sockaddr_in my_addr, their_addr;


    int numbites;
    char* buf[1024], s_buf[1024];

    pthread_t sock_thr;
    int i_sock_thr;




    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
        perror("Server-socket() error!");
        exit(1);
    } else
        printf("Server-socket() sockfd is OK!\n");

    my_addr.sin_family = AF_INET;
    my_addr.sin_port = htons(MYPORT);
    my_addr.sin_addr.s_addr = INADDR_ANY;
    //memset(&(my_addr.sin_zero), 0, 8);
    bzero(&(my_addr.sin_zero), 8);

    //BIND
    if (bind(sockfd, (struct sockaddr *) & my_addr, sizeof (struct sockaddr)) == -1) {
        perror("Server-bind() error!");
        exit(1);
    } else
        printf("bind() is OK!\n");

    //LISTEN
    if (listen(sockfd, BACKLOG) == -1) {
        perror("listen() error!");
        exit(1);
    } else
        printf("listen() is OK!\n");


    i_sock_thr = pthread_create(&sock_thr, NULL, comunicate_ptr, (void*) sockfd);








    printf("Text to send: ");
    //gets(s_buf);

    //    send(new_fd, /*s_buf*/"Oh Yeah, Babe!\n", 16/*strlen(s_buf)*/, 0);





    //    numbites = recv(new_fd, buf, 1023, 0);

    buf[numbites] = '\0';
    printf("Server-Received: %s\n", buf);



    //close(new_fd);
    close(sockfd);



    printf("\n");
    return (EXIT_SUCCESS);
}

void comunicate_ptr(void *sock) {
    int sockfd, new_fd;
    int sin_size;
    struct sockaddr_in their_addr;

    sockfd = (int) sock;

    //ACCEPT
    sin_size = sizeof (struct sockaddr_in);
    new_fd = accept(sockfd, (struct sockaddr*) & their_addr, &sin_size);

    if (new_fd == -1)
        perror("accept() error!");
    else
        printf("accept() is OK!\n");

}